import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { AttemptCustomer } from '@libs/db/models/attempt.model';
import { IPaginationFormWithCondition } from 'types/requestParams';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { formatAgragateCondition, formatDate } from 'utils';
import { EmailService } from 'src/email/email.service';
const path = require('path');
const Searcher = require('libs/xdb/index.js');
const dbPath = path.join(__dirname, '../libs/xdb/ip2region.xdb');

@Injectable()
export class AttemptCustomerService {
  constructor(
    @InjectModel('AttemptCustomer')
    private readonly customerModel: Model<AttemptCustomer>,
    private readonly emailService: EmailService,
  ) {}
  async create(body: any, ip) {
    try {
      const date = new Date();
      const searcher = Searcher.newWithFileOnly(dbPath);
      const data = await searcher.search(ip);
      const playload = {
        ip,
        cityName: data.region,
        hours: date.getHours(),
        day: date.getDate(),
        month: date.getMonth() + 1,
        year: date.getFullYear(),
        ...body,
      };
      const doc = await this.customerModel.create(playload);
      await doc.save();
      this.emailService.sendEmail(body);
      return '保存成功';
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST);
      } else {
        throw new HttpException(
          '服务器内部错误',
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      }
    }
  }

  async findToday(body: IPaginationFormWithCondition) {
    try {
      const dayFormat = formatDate(new Date());
      const todayStart = body.startTime
        ? new Date(body.startTime)
        : new Date(dayFormat);
      const todayEnd = body.endTime
        ? new Date(body.endTime)
        : new Date(dayFormat + ' 23:59:59');
      const total = await this.customerModel.find({}).count();
      const res = await this.customerModel.find({
        cityName: { $regex: body.cityName ?? '' }, // 位置区域
        corporation: { $regex: body.corporation ?? '' }, // 单位名称
        createdAt: { $lte: todayEnd, $gte: todayStart }, // 创建日期
      });
      if (res && total) {
        return {
          rows: res,
          total,
        };
      } else {
        return [];
      }
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST);
      } else {
        throw new HttpException(
          '服务器内部错误',
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      }
    }
  }

  // 查询全部客户信息
  async findAll(body: IPaginationFormWithCondition) {
    try {
      const ands = [
        { cityName: { $regex: body.cityName ?? '' } },
        { corporation: { $regex: body.corporation ?? '' } },
        { telephone: { $regex: body.telephone ?? '' } },
        { customerName: { $regex: body.customerName ?? '' } },
      ];
      const condition = formatAgragateCondition(
        ands,
        body.pageNum,
        body.pageSize,
      );
      const result = await this.customerModel.aggregate(JSON.parse(condition));
      return result[0];
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST);
      } else {
        throw new HttpException(
          '服务器内部错误',
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      }
    }
  }

  async findOne(id: number) {
    try {
      return 'ok';
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST);
      } else {
        throw new HttpException(
          '服务器内部错误',
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      }
    }
  }

  async update(body: AttemptCustomer) {
    try {
      const res = await this.customerModel.findByIdAndUpdate(body._id, body);
      return '更新成功';
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST);
      } else {
        throw new HttpException(
          '服务器内部错误',
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      }
    }
  }

  async remove(id: number) {
    try {
      await this.customerModel.findByIdAndDelete(id).exec();
      return '删除成功';
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST);
      } else {
        throw new HttpException(
          '服务器内部错误',
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      }
    }
  }
}
